import { Context } from 'koa';
import Joi from 'joi';
import TenantPermissionService from '@/services/TenantPermissionService';
import * as response from '@/utils/response';
import { validate, commonSchemas } from '@/utils/validator';
import type { AppContext } from '@/types';

/**
 * 租户权限控制器
 */
export class TenantPermissionController {
  /**
   * 获取租户权限列表
   */
  async list(ctx: Context) {
    const appCtx = ctx as AppContext;
    const user = appCtx.state.user;
    
    if (!user || !user.tenantId) {
      ctx.throw(401, '未授权');
      return;
    }

    const permissions = await TenantPermissionService.getTenantPermissionDetails(
      user.tenantId,
    );

    response.success(ctx, permissions);
  }

  /**
   * 按模块分组获取租户权限
   */
  async listByModule(ctx: Context) {
    const appCtx = ctx as AppContext;
    const user = appCtx.state.user;
    
    if (!user || !user.tenantId) {
      ctx.throw(401, '未授权');
      return;
    }

    const groupedPermissions = await TenantPermissionService.getTenantPermissionsByModule(
      user.tenantId,
    );

    response.success(ctx, groupedPermissions);
  }

  /**
   * 授予额外权限（超级管理员）
   */
  async grantExtra(ctx: Context) {
    const appCtx = ctx as AppContext;
    const user = appCtx.state.user;
    
    if (!user) {
      ctx.throw(401, '未授权');
      return;
    }

    const schema = Joi.object({
      tenantId: commonSchemas.uuid.required(),
      permissionIds: Joi.array()
        .items(commonSchemas.uuid)
        .min(1)
        .required(),
      expiresAt: Joi.date().optional(),
    });

    const data = await validate<{
      tenantId: string;
      permissionIds: string[];
      expiresAt?: Date;
    }>(ctx.request.body, schema);

    await TenantPermissionService.grantExtraPermissions(
      data.tenantId,
      data.permissionIds,
      user.id,
      data.expiresAt,
    );

    response.success(ctx, null, '权限授予成功');
  }

  /**
   * 撤销额外权限（超级管理员）
   */
  async revokeExtra(ctx: Context) {
    const schema = Joi.object({
      tenantId: commonSchemas.uuid.required(),
      permissionIds: Joi.array()
        .items(commonSchemas.uuid)
        .min(1)
        .required(),
    });

    const data = await validate<{
      tenantId: string;
      permissionIds: string[];
    }>(ctx.request.body, schema);

    await TenantPermissionService.revokeExtraPermissions(
      data.tenantId,
      data.permissionIds,
    );

    response.success(ctx, null, '权限撤销成功');
  }

  /**
   * 同步套餐权限
   */
  async syncPlanPermissions(ctx: Context) {
    const schema = Joi.object({
      tenantId: commonSchemas.uuid.required(),
    });

    const data = await validate<{ tenantId: string }>(ctx.request.body, schema);

    await TenantPermissionService.syncPlanPermissions(data.tenantId);

    response.success(ctx, null, '套餐权限同步成功');
  }

  /**
   * 获取指定租户的权限（超级管理员）
   */
  async getTenantPermissions(ctx: Context) {
    const schema = Joi.object({
      tenantId: commonSchemas.uuid,
    });

    const params = await validate<{ tenantId: string }>(ctx.params, schema);

    const permissions = await TenantPermissionService.getTenantPermissionDetails(
      params.tenantId,
    );

    response.success(ctx, permissions);
  }
}

export default new TenantPermissionController();

